package com.flying.arts.trade.controller;

import com.flying.arts.trade.domain.entity.MatchedTrade;
import com.flying.arts.trade.domain.service.MatchedTradeService;
import com.flying.arts.common.domain.entity.Entity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@RestController
@RequestMapping("/v1/matchedtrade")
public class MatchedTradeController {
    private Logger logger = LoggerFactory.getLogger(MatchedTradeController.class);
    private MatchedTradeService service;

    @Autowired
    public MatchedTradeController(MatchedTradeService service) {
        this.service = service;
    }

    @GetMapping
    public ResponseEntity<Collection<MatchedTrade>> findByStockName(@RequestParam("stockname") String name) {
        logger.info(String.format("trade-service findByStockName() invoked:{%s} for {%s} ", service.getClass().getName(), name));
        name = name.trim().toLowerCase();
        Collection<MatchedTrade> restaurants;
        try {
            restaurants = service.findByStockName(name);
        } catch (Exception e) {
            logger.error("Exception raised findByStockName REST call", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return restaurants.size() > 0 ? new ResponseEntity<>(restaurants, HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity<Entity> findById(@PathVariable("id") long id) {
        logger.info(String.format("trade-service findById() invoked:{%s} for {%s} ", service.getClass().getName(), id));
        Entity trade;
        try {
            trade = service.findById(id);
        } catch (Exception e) {
            logger.error("Exception raised findById REST call {0}", e);
            return new ResponseEntity<Entity>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return trade != null ? new ResponseEntity<>(trade, HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PostMapping
    public ResponseEntity<MatchedTrade> add(@RequestBody MatchedTrade trade) {
        logger.info(String.format("trade-service add() invoked: %s for %s", service.getClass().getName(), trade.getId()));
        try {
            service.add(trade);
        } catch (Exception e) {
            logger.error("Exception raised add Restaurant REST Call {0}", e);
            return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
}